//
//  HWRankListViewController.swift
//  HWanGame
//
//  Created by Apple on 2024/8/10.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView

class ClubRankListViewController: ClubBaseViewController {

    private var topView = ClubRankListTopView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubRankCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 90.0.Scale
        return tableView
    }()

    var tempModel:[ClubHomeGameModel]?{
        didSet{
            guard let allGames = tempModel, allGames.count > 0 else {
                self.tableView.reloadData()
                return
            }
            var models = [ClubHomeGameModel]()
            for (index, md) in allGames.enumerated() {
                var model = md
                model.sort = index
                models.append(model)
            }
            self.dataModel = models
            tableView.reloadData()
        }
    }
    var dataModel:[ClubHomeGameModel]?
    
    
    private var pageIndex = 1
    private var gameType:String = "0"
    
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        
//    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        view.backgroundColor = "#F7F8FA".toColor
        view.subviews{
            topView
            tableView
        }
        
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }

        topView.leading(0).trailing(0).top(0).height(38.0.Scale)
        tableView.leading(0).trailing(0).bottom(0).top(38.0.Scale)
        topView.updateCateData = { type in
            self.tableView.resetNoMoreInfo()
            self.gameType = type
            self.loadNewData()
        }
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
    }
    
}

//MARK: - loadData
extension ClubRankListViewController {

    private func loadData(){
        
        Task {
            if ClubGlobalTool.shared.newGameList {
                self.gameType = "3"
            }
            let models = await self.network.request(.home(type: "5", gameType: self.gameType, page: pageIndex),type: ClubHomeNormalModel.self)
            if models.isSuccess, let model = models.model {
                self.tempModel = model.allGames?.games
                var tempArray = model.game_types
                if ClubGlobalTool.shared.newGameList {
                    var tempArr = [ClubHomeNormalGameTypeModel]()
                    for md in tempArray {
                        var mod = md
                        if mod.id == "3" {
                            mod.isSel = true
                        }else{
                            mod.isSel = false
                        }
                        tempArr.append(mod)
                    }
                    self.topView.sourceData = tempArr
                    ClubGlobalTool.shared.newGameList = false
                }else{
                    if self.gameType == "0" || self.gameType == "2" {
                        tempArray[0].isSel = true
                    }else if self.gameType == "4" {
                        tempArray[1].isSel = true
                    }else if self.gameType == "3" {
                        tempArray[2].isSel = true
                    }
                    self.topView.sourceData = tempArray
                }
            }
        }
    }
    
    @objc private func loadNewData(){
        pageIndex = 1
        self.tempModel?.removeAll()
        self.dataModel?.removeAll()
        self.tableView.reloadData()
        ToastUtil.show()
        Task {
            let models = await network.request(.home(type: "5", gameType: self.gameType, page: pageIndex),type: ClubHomeNormalModel.self)
            ToastUtil.dismiss()
            tableView.refresh_end()
            if models.isSuccess, let model = models.model {
                self.tempModel = model.allGames?.games
//                self.tableView.reloadData()
            }
        }
    }
    
    @objc private func loadMoreData(){
        pageIndex += 1
        Task {
            let models = await network.request(.home(type: "5", gameType: self.gameType, page: pageIndex),type: ClubHomeNormalModel.self)
            tableView.refresh_end()
            if models.isSuccess, let model = models.model {
                if (model.allGames?.games?.count ?? 0) > 0 {
                    for mod in (model.allGames?.games)! {
                        self.tempModel?.append(mod)
                    }
                } else {
                    self.tableView.refresh_end(true)
                }
//                self.tableView.reloadData()
            }
        }
    }
}


//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubRankListViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return dataModel?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubRankCell", for: indexPath) as! ClubRankCell
        if dataModel?.count ?? 0 > indexPath.row {
            cell.model = dataModel?[indexPath.row]
        }
        cell.gameType = self.gameType
        cell.yuyueGameBlock = { id in
            guard let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 else {
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                return
            }
            Task{
                let res = await self.network.request(.addAppointment(gid: id),isShowError: false)
                if res.isSuccess {
                    self.loadNewData()
                }
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let gameId = dataModel?[indexPath.row].id ?? ""
        let detailVC = ClubGameDetailViewController()
        detailVC.gameId = gameId
        self.navigationController?.pushViewController(detailVC, animated: true)
    }

}

extension ClubRankListViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
